<template>
	<view class="container">
		<!-- 自定义顶部栏（替代原生导航栏） -->
		<view class="custom-nav-bar">
			<view class="title-container">
				<text class="title">面向分析</text>
				<text class="subtitle">智引未来</text>
			</view>
		</view>
		<!---->

		<!-- 图片展示区域 -->
		<view class="image-section">
			<image class="preview-image" :src="currentImage" mode="aspectFit" @click="handleUpload"></image>
		</view>

		<!-- 说明部分 -->
		<view class="section">
			<text class="section-title">说明</text>

			<view class="content">
				<text class="content-item">1. 建议使用清晰的正脸照片，图片分辨率：最小600 * 800，最大4096 * 4096。</text>
				<text class="content-item">2. 我们不会采集或留存任何用户个人信息，建议您及时保存生成的内容和图片。</text>
			</view>
		</view>

		<!-- 分割线 -->
		<u-line color="#e4e7ed" margin="30rpx 0"></u-line>

		<!-- 上传按钮 -->
		<view class="upload-section">
			<u-button type="primary" shape="circle" @click="handleButtonClick">
				{{ isImageUploaded ? '提交分析' : '上传图片' }}
			</u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				urlPath: '',
				isImageUploaded: false, // 新增变量：是否已选择并上传图片
				currentImage: this.$baseURL + "/profile/upload/2025/05/10/image_20250507102305A034_20250510150119A023.png",
				query: `你是一位优秀的面相大师和心理专家，这是一个用户的自己的画像相册，请你根据这个用户相册的个人微表情之类的来分析用户的心情，给我一个对这个用户的心理评价和对应的情绪分数，你需要返回给我一个["72","31","56","66","42","83"]这样的数组,这几个数据是对['高兴','充实','伤心','孤独','迷茫','纠结']这几个情绪的评分，总分一百分，然后在给我对这个女孩的情绪评价，例如："这张照片看起来充满活力和热情。你可能在此时节心情愉悦，因为面部表情微笑代表新开心、希望和追求。"`,
				usedTime: null,
				startTime: null
			}
		},
		onReady() {
			//开始计时
			this.startTime = Date.now()
		},
		methods: {
			handleButtonClick() {
				if (this.isImageUploaded) {
					this.handResult();
				} else {
					this.handleUpload();
				}
			},
			handResult() {
				uni.navigateTo({
					url: '/pages/psychologyModel/drawingAnalysis/drawing/drawingResult',
					success: (res) => {
						//计算截至时间
						if (this.startTime) {
							console.log('111')
							const startTime1 = (typeof this.startTime === 'number' && this
									.startTime < 1e12) ?
								this.startTime * 1000 :
								this.startTime;
							const endTime = Date.now();
							let durationSeconds = Math.floor((endTime - startTime1) /
								1000);
							if (durationSeconds < 0 || isNaN(durationSeconds))
								durationSeconds = 0;
							this.usedTime = this.formatDuration(durationSeconds);
						} else {
							console.log(this.startTime)
							console.log('222')
							this.usedTime = '未记录';
							console.log('⚠️ startTime 获取失败');
						}
						// 通过 eventChannel 向目标页面传参
						res.eventChannel.emit('result', {
							aiUrl: this.urlPath,
							usedTime: this.usedTime,
							query: this.query
						});
					}
				});
			},


			handleUpload() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						// 替换当前显示的图片
						this.currentImage = res.tempFilePaths[0];
						this.isImageUploaded = false; // 清空之前状态
						console.log(this.currentImage)
						uni.showToast({
							title: '图片已选择',
							icon: 'success'
						});

						const token = uni.getStorageSync('token'); // 直接取本地缓存 token
						uni.uploadFile({
							url: 'http://ip-pppoe-liaoning-07.xyzy.eu.org:5532/common/upload', // 你后端的上传地址
							filePath: this.currentImage,
							name: 'file', // 后端接收字段名
							header: {
								'Authorization': 'wx' + token, // 如果后端要求 Authorization
							},
							success: (uploadRes) => {
								console.log('上传成功:', uploadRes);
								uni.showToast({
									title: '上传成功',
									icon: 'success'
								});
								const result = JSON.parse(uploadRes.data);
								console.log(result);
								this.urlPath = result.url
								this.isImageUploaded = true; // 标记上传完
							},
							fail: (err) => {
								console.error('上传失败:', err);
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								});
							}
						});
					}
				});
			},
			formatDuration(seconds) {
				// 把秒数格式化成几分几秒
				const m = Math.floor(seconds / 60)
				const s = seconds % 60
				return `${m}分${s}秒`
			},
		},
	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: #fff;
		min-height: 100vh;
	}

	.custom-nav-bar {
		padding: 20rpx 30rpx;
		background-color: rgb(248, 248, 248);
		color: white;
		text-align: center;
		padding-top: var(--status-bar-height);
		display: flex;
		align-items: center;
		position: relative;
	}

	.title-container {
		margin-top: -20rpx;
		flex: 1;
		text-align: center;
	}

	.custom-nav-bar .title {
		font-size: 35rpx;
		font-weight: bold;
		display: block;
		color: #000000;
	}

	.custom-nav-bar .subtitle {
		font-size: 25rpx;
		display: block;
		margin-top: 10rpx;
		color: #000000;
	}

	/* 图片展示区域 */
	.image-section {
		padding: 30rpx;
		display: flex;
		justify-content: center;
	}

	.preview-image {
		width: 100%;
		height: 400rpx;
		border-radius: 16rpx;
		background-color: #f5f5f5;
	}

	/* 其余部分样式 */
	.section {
		padding: 30rpx;
		margin-bottom: 30rpx;
	}

	.section-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}

	.content {
		padding-left: 20rpx;
	}

	.content-item {
		display: block;
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
		margin-bottom: 15rpx;
	}

	.upload-section {
		padding: 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 40rpx;
	}
</style>